package com.qf.config;

import com.qf.service.AuthService;
import com.qf.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @author YDW
 * projectName:project2202_4
 * time:2022/7/6 10:36
 * description:
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {


    @Autowired
    AuthService authService;

    /*
    * 过滤请求
    * 1. 判断是否是登录请求，如果是，则放行（直接请求认证微服务）
    * 2. 如果不是登录请求，从request对象中获取cookie信息
    *   2.1 如果可以获取到token，且token合法，则放行
    *   2.2 如果获取不到token，或者token不合法，返回状态401（未认证）
    * */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取请求路径,如果请求路径包含login，则认为是登录请求
        if (request.getURI().getPath().contains("/login")) {
            //放行，正常执行认证操作
            return chain.filter(exchange);
        }
        //从cookie获取token数据
        String token=authService.findJwtTokenFromCookie(request,"jwtToken");
        //对token进行判断
        if(StringUtils.isEmpty(token)){
            //如果token为null，则说明没有登录
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }else {
            try {
                //解析token，获取自定义数据（包含了用户角色权限等信息）
                Claims claims = JwtUtil.parseJWT(token);
                return chain.filter(exchange);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("jwt Token被篡改");
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();

            }
        }

    }

    //控制过滤器的执行顺序，数字越小越先执行
    @Override
    public int getOrder() {
        return 1;
    }
}
